package hot100.logos61To70;

/**
 * @author logos
 * date 2025/7/16 17:42
 * @version v1.0
 * @Package hot100.logos61To70
 */
public class logos65 {

    /**
     * 65. 在排序数组中查找元素的第一个和最后一个位置
     * https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/description/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int start = binarySearch(nums, target);
            if (start == nums.length || nums[start] != target) {
                return new int[] { -1, -1 };
            }
            int end = binarySearch(nums, target + 1) - 1;
            return new int[] { start, end };
        }

        private int binarySearch(int[] nums, int target) {
            int left = 0;
            int right = nums.length - 1;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] >= target) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            return left;
        }
    }
}
